Skip to content

feat: feature refresh listeners on both clients - #142

Open
vazarkevych wants to merge 7 commits into
growthbook:mainfrom
vazarkevych:feat/feature-refresh-listeners
Open

vazarkevych wants to merge 7 commits into
growthbook:mainfrom
vazarkevych:feat/feature-refresh-listeners

Conversation

@vazarkevych

@vazarkevych vazarkevych commented Sep 15, 2026 •

Copy link
Copy Markdown
Collaborator

What and why

Applications had no supported way to react to a feature payload being applied. The sync client exposed it only on the module-level feature_repo singleton, the async client only through the private client._features_repository.

What changed

  • New API on GrowthBook and GrowthBookClient: add_feature_refresh_listener(listener) returns an unsubscribe callable; remove_feature_refresh_listener(listener) also works. The async client accepts plain and coroutine functions.

    unsubscribe = gb.add_feature_refresh_listener(
        lambda payload: log.info("features updated: %d", len(payload.get("features", {})))
    )
  • Semantics: listeners get the raw payload after it is applied, so evaluating inside a listener sees the new definitions. A raising listener is logged and skipped. A failed refresh notifies nothing.

  • Once per refresh (sync): a payload is skipped if it is the same object or has the same content as the last one delivered. Content comparison keeps JSON types apart (True ≠ 1 ≠ 1.0), so caches that return a copy each time, like the README's Redis cache, don't refire listeners.

  • Ordering and re-entry: apply and notify run as one unit, so overlapping refreshes arrive in apply order. A listener may refresh features itself (directly or from a task): the remaining listeners get only the newer payload, and nothing older than the applied state is delivered. The async client notifies outside the context lock, so there is no deadlock.

  • SSE (sync): streamed payloads now notify listeners. They are cached before listeners run. A failed cache write is logged and the update is still applied.

  • Cleanup: close() / destroy() clear listeners.

  • Remote-eval: the async client emits no events (payloads there are per-user); possible follow-up on top of feat: user-scoped GrowthBookClient instances via create_scoped_instance #141.

  • README: new "Feature Refresh Listeners" section.

How to test

pytest tests/test_growthbook.py tests/test_growthbook_client.py -k "refresh or sse_payload"

17 new tests (21 cases) covering both clients: once per refresh, copying caches, bool/number changes, SSE delivery and cache-write failures, unsubscribe and errors, close(), concurrent refreshes, and re-entrant refreshes without deadlock or reordering.

Full suite: 1962 passed. The 2 cache fixture errors in test_growthbook_client.py also happen on main.

Size

Production code +276 / −6, tests +546, README +43. Over 800 lines, mostly tests.

Migration

None. Nothing changes unless a listener is registered.

@greptile-apps

greptile-apps Bot commented Sep 15, 2026 •

Copy link
Copy Markdown

Confidence Score: 5/5RetriggerView in Greptile

[Medium impact] The pull request appears safe to merge, with no outstanding correctness, security, or repository-rule issues identified.

Reviews (9) · Last reviewed commit: "Merge remote-tracking branch 'origin/mai..." · Reviewed by Greptile

Comment thread growthbook/growthbook.py Resolved
Comment thread growthbook/growthbook.py Resolved
Comment thread growthbook/growthbook_client.py Resolved
@vazarkevych

Copy link
Copy Markdown
Collaborator Author

All three are valid — fixed in the force-push.

Failed Refresh Replays Payload. Confirmed: _notify_feature_refresh(None)
cleared _last_refresh_payload, so the next cache hit returned the same
previously-notified object and fired listeners again. A failed refresh applies
nothing, so it now leaves the marker alone.

Concurrent Refreshes Reorder Events. Also confirmed — and worth noting the
obvious fix isn't enough: taking the lock only around the notification still
allows apply A → apply+notify B → notify A. The pair has to be held together.
Sync does that under the reentrant payload-writer lock, which evaluation never
takes. Async can't reuse the context lock — evaluation holds it, so notifying
under it deadlocks any listener that evaluates — so it gets a separate ordering
lock that evaluation never touches.

Close Retains Refresh Listeners. Fixed; close() now clears the list under
its lock, matching subscriptions.

Three regression tests, each failing without its fix. The ordering one runs six
concurrent refreshes with an await inside the callback and asserts every
listener call sees the context matching its own payload. Also rebased onto
current main. 1203 tests pass, mypy/pyright clean

@andywhite37
andywhite37 self-requested a review October 8, 2026 21:28
@andywhite37 andywhite37 added effort:large Substantial review and testing, often across APIs, components, or environments. needs-human-input A specific decision or manual task blocks progress; see the queue entry. priority:normal Regular queue priority; no evidence of urgency or low value. risk:medium Changes behavior with a bounded impact that needs focused validation. labels Oct 20, 2026
@andywhite37

Copy link
Copy Markdown
Contributor

Maintainer decision needed: confirm the refresh-listener contract before implementation review. Listeners receive the raw payload after it is applied, and async listeners are awaited in order, so a slow listener delays later refresh notifications. The async remote-evaluation path does not emit these events, while the synchronous client can emit them for user-specific payloads. Please record the intended ordering, callback/re-entry expectations, and remote-evaluation coverage, coordinating the shared-client changes with #114 and #141.

@vazarkevych

vazarkevych commented Oct 21, 2026 •

Copy link
Copy Markdown
Collaborator Author

Recording the contract. One of your four points turned out to be broken rather than just undocumented, so that's fixed in the force-push.

  1. Payload and timing. Listeners get the raw payload dict after it has been applied, so evaluating inside a callback sees the new definitions. Dispatch is keyed on payload identity: once per refresh, not once per evaluation (evaluation calls load_features() constantly and usually gets a cache hit, which returns the same object). A failed refresh applies nothing and notifies nothing.

  2. Ordering is guaranteed, and the cost is back-pressure. Apply and notify are held together — reentrant payload lock in sync, a dedicated ordering lock in async — so two overlapping refreshes can't deliver out of application order. The consequence you spotted is real and intended: async listeners are awaited in sequence, so a slow listener delays the next refresh, not just the next notification. The alternative (fire-and-forget tasks) drops the ordering guarantee, which is what the bot flagged as P1. Listeners should stay cheap; offload real work to a task.

  3. Re-entry works on both clients. A listener may call set_payload/set_features/load_features: the newer payload is applied immediately, the remaining listeners receive only the newer one, and delivery restarts with it — so no listener is handed a payload older than the applied state. Async re-entry is detected via a context variable carrying the running dispatch’s token (a task the listener awaits counts too); a concurrent refresh from another task still waits for the ordering lock. Fixed in f412be9 with regression tests for both clients, which fail without the fix (async by timeout).

  4. Remote-eval coverage is deliberately asymmetric. The async client emits nothing in remote-eval mode: payloads there are per-user, so there is no client-wide "definitions changed" moment — a listener would fire once per user and mean something different each time. The sync client is per-user, so it does emit. If you'd rather have the async events too, the natural home is the scoped handle from feat: user-scoped GrowthBookClient instances via create_scoped_instance #141, not the shared client.

On coordination: #114 touches FeatureRepository caching and #141 adds the scoped handle; neither overlaps these code paths, and all three are rebased on current main. Happy to reorder if you want them landed in a particular sequence.

Applications had no supported way to react to a feature payload being applied.
The plumbing existed but wasn't reachable: the sync path exposed it only on the
module-level feature_repo singleton, and the async path only through
client._features_repository, a private attribute, with an async-only callback.

Adds add_feature_refresh_listener / remove_feature_refresh_listener to both
GrowthBook and GrowthBookClient. The add method returns a callable that
unregisters the listener. Listeners receive the raw payload dict and run after
it has been applied, so evaluating from inside a listener already sees the new
definitions. A listener that raises is logged and skipped. The async client
accepts plain functions and coroutine functions alike.

Also fixes a gap on the way: the sync streaming path applied payloads and wrote
the cache without notifying anything, so in SSE mode — the case this feature
exists for — nothing observed the update.

Three ordering and lifecycle details, each with a regression test:

Dispatch is keyed on payload identity, so listeners fire once per refresh
rather than once per evaluation (evaluation calls load_features() constantly
and usually gets a cache hit, which returns the same object).

A failed refresh no longer clears that identity marker. It applies nothing, so
the payload listeners last saw is unchanged; clearing it made the next cache
hit — which returns that same previously-notified object — look fresh and fire
listeners a second time.

Apply and notify happen as one unit. In the sync client that is the reentrant
payload-writer lock, which evaluation never takes. In the async client it is a
separate ordering lock, since evaluation takes the context lock and notifying
under that one deadlocks any listener that evaluates. Without this, two
overlapping refreshes could apply A, apply and notify B, then notify A —
handing listeners an older payload last and letting a listener see state that
doesn't match the payload it was given.

GrowthBookClient.close() clears the listener list, matching subscriptions and
the sync client. Listener closures capture application objects, and a
reinitialized client would otherwise fire callbacks from its previous
lifecycle.
@vazarkevych
vazarkevych force-pushed the feat/feature-refresh-listeners branch from 604849b to 6d8aef0 Compare November 10, 2026 13:28
@vazarkevych

Copy link
Copy Markdown
Collaborator Author

@greptile review

Comment thread growthbook/growthbook.py Resolved
Comment thread growthbook/growthbook_client.py Resolved
A listener that updated features re-entered the dispatch:

- Async client: _feature_update_callback waited for the ordering lock
  that its own dispatch held, so a listener calling set_payload,
  set_features or initialize hung the client.
- Sync client: the reentrant payload lock let the nested refresh deliver
  the newer payload to every listener before the outer loop resumed, so
  the remaining listeners got the older payload last, while evaluation
  already used the newer one.

A refresh started from a listener now only applies its payload. The
running dispatch delivers it: the remaining listeners get only the newer
payload, and delivery starts over with it. The sync client recognises
re-entry by a flag held under its payload lock. The async client uses a
context variable carrying the running dispatch's token, so a task the
listener awaits counts as re-entry too, while a concurrent refresh still
waits for the lock.

Regression tests cover both clients; each fails without the fix (the
async ones by timeout).
@vazarkevych

Copy link
Copy Markdown
Collaborator Author

@greptile review

Comment thread growthbook/growthbook_client.py Resolved
A task that a listener starts without awaiting inherits the dispatch
context, so its set_payload() takes the re-entry path and skips the
ordering lock. If the dispatch finished while the task was still
applying, the payload was applied but never delivered to listeners.

After a re-entrant apply, if no dispatch is running any more, the task
now takes the ordering lock and dispatches the payload itself, unless a
newer payload has replaced it or another dispatch already delivered it.
@vazarkevych

Copy link
Copy Markdown
Collaborator Author

@greptile review

1 similar comment
@vazarkevych

Copy link
Copy Markdown
Collaborator Author

@greptile review

…listeners

# Conflicts:
#	growthbook/growthbook_client.py
@vazarkevych

Copy link
Copy Markdown
Collaborator Author

@greptile review

Comment thread growthbook/growthbook.py Resolved
Comment thread growthbook/growthbook.py Resolved
_notify_feature_refresh skipped a payload only when it was the same object
as the last one dispatched. A cache that decodes on every hit, like the
README's Redis cache, returns a new dict each time, so every
load_features() fired the listeners again, and a listener that loads
features itself kept the delivery loop from ever finishing. Also skip a
payload equal to the last one.

The SSE handler applied and dispatched the streamed payload before
caching it. A listener calling load_features() then got the previous
payload from the cache and reapplied it over the update. Cache the
payload first.
@vazarkevych

Copy link
Copy Markdown
Collaborator Author

@greptile review

Comment thread growthbook/growthbook.py Resolved
Comment thread growthbook/growthbook.py Resolved
…ache errors

The content check that skips repeated payloads used ==, which treats
True == 1, False == 0 and 1 == 1.0 as equal. A setting changing between
those values was applied but never reached the refresh listeners. Compare
payloads structurally with types kept apart instead.

The SSE handler now caches before applying, so a failing custom cache
(e.g. a Redis outage) raised before the update was applied, and the
stream does not retry the event. Log the failed write and apply the
payload anyway.
@vazarkevych

Copy link
Copy Markdown
Collaborator Author

@greptile review

…listeners

# Conflicts:
#	tests/test_growthbook.py
@vazarkevych

Copy link
Copy Markdown
Collaborator Author

@greptile review

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

effort:large Substantial review and testing, often across APIs, components, or environments. needs-human-input A specific decision or manual task blocks progress; see the queue entry. priority:normal Regular queue priority; no evidence of urgency or low value. risk:medium Changes behavior with a bounded impact that needs focused validation.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants